﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using STX.Admin.Models.BizApply;
using STX.Domain;
using STX.Service;

namespace STX.Admin.Controllers
{
    public class BizApplyController : BasePages1Controller<BizApply, IndexModel, AddModel, EditModel, QueryModel>
    {
        public BizApplyService BizApplyService { get; set; }



        protected override void OnInit(out Func<BaseService<BizApply>> thisService,
            out Func<IndexModel> getIndexModelFunc, out Func<AddModel> getAddModelFunc,
            out Func<int, EditModel> getEditModelFunc)
        {
            thisService = () => BizApplyService;
            getIndexModelFunc = () => new IndexModel();
            getAddModelFunc = () => new AddModel();
            getEditModelFunc = i =>
            {
                var model = BizApplyService.FindModelById(i);
                if (model == null)
                {
                    throw new Exception("未找到此条数据");
                }
                return new EditModel
                {
                    Id = model.Id,
                    Content = model.Msg,
                    Title = model.Title
                };
            };
        }

        protected override long AddHandler(AddModel addModel)
        {
            var model = new BizApply
            {
                UserId = AdminContext.CurrentUser.Id,
                AddTime = DateTime.Now,
                Msg = addModel.Content,
                SendTo = addModel.Position,
                Title = addModel.Title,
                Status = BizApply.ApplyStatusEnum.未审批
            };
            return BizApplyService.Add(model);
        }

        protected override bool EditHandler(EditModel editModel)
        {
            var model = BizApplyService.FindModelById(editModel.Id);
            if (model == null)
            {
                throw new Exception("未找到此条数据");
            }
            model.Reply = editModel.Reply;
            model.Status = BizApply.ApplyStatusEnum.已审批;
            return BizApplyService.Update(model);
        }

        public ActionResult Detail(int id)
        {
            var model = BizApplyService.FindModelById(id);
            if (model == null)
            {
                throw new Exception("未找到此条数据");
            }
            var dto = new EditModel
            {
                Id = model.Id,
                Content = model.Msg,
                Title = model.Title,
                Reply = model.Reply
            };
            return View(dto);
        }

        protected override IQueryable<BizApply> QueryHandler(QueryModel queryModel, IQueryable<BizApply> queryable)
        {
            if (!queryModel.Name.IsNullOrEmpty())
                queryable = queryable.Where(o => o.Title.Contains(queryModel.Name));
            return queryable;
        }
    }
}
